package com.ne.alice;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class FileNIOCopyDemo {
    public static void main(String[] args) {
        nioCopyResourceFile();
    }

    public static void nioCopyResourceFile(){
        String sourcePath = "d://操作系统导论.pdf";
        String destPath = "d://b.pdf";
        nioCopyFile(sourcePath,destPath);
    }

    public static void nioCopyFile(String srcPath,String destPath){
        long startTime = System.currentTimeMillis();
        File srcFile = new File(srcPath);
        File destFile = new File(destPath);
        FileInputStream fis = null;
        FileOutputStream fos = null;
        FileChannel inChannel = null;
        FileChannel outChannel = null;
        try{
            fis = new FileInputStream(srcFile);
            fos = new FileOutputStream(destFile);
            inChannel = fis.getChannel();
            outChannel = fos.getChannel();
            int length = -1;
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            while ((length = inChannel.read(buffer))!=-1){
                buffer.flip();
                int outLength = 0;
                while ((outLength = outChannel.write(buffer))!=0){
                    System.out.println("写入的字节："+outLength);
                }
                buffer.clear();
            }
            outChannel.force(true);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                outChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                inChannel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fis.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("用时：" + (endTime - startTime) + "毫秒");
    }
}
